package red.mlz.uploadservice.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import red.mlz.common.utils.BaseUtils;
import red.mlz.uploadservice.service.OssService;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@RestController
public class UploadController {
    @Autowired
    private OssService ossUtils;

    @PostMapping(value = "/upload" , consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String uploadFile(@RequestPart("file") MultipartFile file) {

        try (InputStream inputStream = file.getInputStream()) {  // 自动关闭流
            // 生成唯一文件名
            String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();
            // 示例路径
            String uploadDir = "D:/uploads/";
            Path uploadPath = Paths.get(uploadDir);

            // 创建目录（如果不存在）
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 保存文件
            Path filePath = uploadPath.resolve(fileName);
            Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);

            return "文件上传成功，路径：" + filePath;
        } catch (Exception e) {
            return "文件上传失败"+ e.getMessage();
        }
    }

    @PostMapping(value = "/oss/upload" , consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String upload(
            @RequestPart("file") MultipartFile file,
            @RequestParam(value = "width", required = false) Integer width,
            @RequestParam(value = "height", required = false) Integer height
    ) {

        try {
            // 基础校验
            if (BaseUtils.isEmpty(file)) {
                return "文件不能为空";
            }

            // 执行上传
            String url = ossUtils.upload(file, width, height);
            return"url"+url;
        } catch (IOException e) {
            return "上传失败: " + e.getMessage();
        }
    }
}
